<?php

class UsersController extends Controller {

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionFunds() {
        $promoCodeID = isset($_GET['promoCode']) ? $_GET['promoCode'] : Promocodes::model()->find('1=1 order by id asc')->id;
        $group = isset($_GET['group']) ? $_GET['group'] : 'd';
        $models = array();
        $sql = 'SELECT
                        f.amount,
                        f.date,	
                        u.user_fname	
                FROM
                        ev_users u
                JOIN ev_user_costs f ON u.user_id = f.user_id :: INT
                WHERE
                u.promo_code :: INT = ' . $promoCodeID . ' ORDER BY f.date DESC';
        (array) $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        foreach ($models as $model) {
            $logs[date('d.m.Y', $model['date'])][] = $model;
        }

//        echo '<pre>';
//        print_r($logs);exit;

        $this->render('funds', array(
            'models' => $logs,
            'promoCodeID' => $promoCodeID,
            'group' => $group,
        ));
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Users;
        $this->pageTitle = 'Cоздать пользователя';
        $model->scenario = 'create';
        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Users'])) {
            $model->attributes = $_POST['Users'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->user_id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $model->scenario = 'update';
        $this->pageTitle = 'Изменение данных о пользователе ' . $model->user_fname;
        $this->performAjaxValidation($model);
        $password = $model->user_password;
        $model->user_password = '';
        if (isset($_POST['Users'])) {
            $model->attributes = $_POST['Users'];
            if (empty($model->user_password))
                $model->user_password = $password;
            if ($model->save()) {
                $this->refresh();
            }
        }
        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();
        $this->redirect(array('index'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {

        $this->pageTitle = 'Список пользователей';
        $c = new CDbCriteria();
        $c->order = 'user_registered desc';
        $count = Users::model()->count($c);
        $pages = new CPagination($count);
        $pages->pageSize = 10;
        $pages->applyLimit($c);
        $models = Users::model()->findAll($c);
        $this->render('index', array(
            'models' => $models,
            'pages' => $pages,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Users('search');
        $this->pageTitle = 'Управление пользователями';
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Users'])) {
            $model->attributes = $_GET['Users'];
        }

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Users the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Users::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Users $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'users-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
